#!/usr/bin/python
# -*- coding: utf-8 -*-
from jbotclass import JBot
import time, os, sys
import simplejson as json
from config import *
import logging
logging.basicConfig(filename="log/ikitobot.log", level=logging.DEBUG)

class Ikitobot(JBot):
    def process_conf_message(self, nick, text):
        pass
    def process_incoming_message(self, from_user, text):
        self.send_to_user(from_user, text)
        pass
    def process_task(self, msg):
        logging.info('process_task called')
        try:
            task = json.loads(msg)
            print 'got correct task'
            logging.info('got correct task')
        except Exception as e: 
            task = {}
            logging.warning('unable to decode task {0}. error: {1}'.format(msg, e))
        if task.get('action', None) == 'vote':
            jabber = task.get('jabber', None)
            track_id = task.get('track_id', None)
            vote = task.get('vote', None)
            if jabber and track_id and vote:
                s = u"user {0} votes {1} for #{2}".format(jabber, vote, track_id)
                self.send_to_conference(s)
                return
        if task == {}:
            self.send_to_conference(msg)
        pass

if __name__ == "__main__":
    daemon = Ikitobot(PID_FILE, stdout=STD_OUT, stderr=STD_ERR)
    if len(sys.argv) == 2:
        if 'run' == sys.argv[1]:
            daemon.run()
        elif 'start' == sys.argv[1]:
            print "ikitobot start!"
            daemon.start()
        elif 'stop' == sys.argv[1]:
            print "ikitobot stop!"
            daemon.stop()
        elif 'restart' == sys.argv[1]:
            print "ikitobot restart!"
            daemon.restart()
        else:
            print "Unknown command"
            sys.exit(2)
        sys.exit(0)
    else:
        print "usage: %s start|stop|restart" % sys.argv[0]
        sys.exit(2)

